package com.chezhujie.www.controller;


import com.chezhujie.www.core.image.ImageUtils;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.*;
import com.chezhujie.www.domain.vo.BusinessAndPic;
import com.chezhujie.www.domain.vo.CommImg;
import com.chezhujie.www.enums.OrderType;
import com.chezhujie.www.service.*;
import com.chezhujie.www.utils.UUIDUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 商家商品
 */
@Controller
@RequestMapping("/busin")
public class CzjbusinessAdminController extends BaseController<Czjbusiness>{
	@Autowired
	private CzjbusinessService czjbusinessService;

	@Autowired
	private CzjcommodityService czjcommodityService;

	@Autowired
	private CzjorderService czjorderService;

	@Autowired
	private CzjcommodityimageService czjcommodityimageService;
	
	@Autowired
	private CzjawardstockService czjawardstockService;
	
	@Autowired
	private CzjcarelaService czjcarelaService;
	
	@Autowired
	private CzjspecificationService czjspecificationService;
	
	
    @Autowired
    private CzjaftersalesService czjaftersalesService;
    
    @Autowired
    private Czjcommodity3Service czjcommodity3Service;
	
	

	@RequestMapping("list")
	public String listBusiness(Integer pageNo, Integer pageSize,
			HttpServletRequest req, HttpServletResponse resp,
			Integer soldOut,String commodityName,Date  createTimeStart,
			HttpSession httpSession, ModelMap model) {

		setBusinessId(model);
		setTypeId(model);
		Map<String, Object> map = new HashMap<String, Object>();
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 20;
		}
			if(null!=soldOut){
				map.put("soldOut", soldOut);
				model.addAttribute("soldOut", soldOut);
			}
			if(null!=commodityName){
				map.put("commodityName", commodityName);
				model.addAttribute("commodityName", commodityName);
			}
			if(null!=createTimeStart){
				map.put("createTimeStart", createTimeStart);
				
				model.addAttribute("createTimeStart", createTimeStart);
			}
			
		try {
			// TODO 获取用户 在获取店铺ID
			/*
			 * Czjbusiness czjbusiness=(Czjbusiness)
			 * httpSession.getAttribute("");
			 */
			Xyuser user= (Xyuser) httpSession.getAttribute("user");
			if(null!=user){
				
				Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(user.getUserId());
				if(null!=czjbusiness){
					map.put("businessId",czjbusiness.getId() );
				}else{
					return  "nobusin/nobusin";
				}
				
				
			}else{
				
				model.addAttribute("error","用户为空");
				return "nobusin/no";
			}
			Pagination pagination = czjcommodityService.list(pageNo, pageSize,
					map, model);

			model.addAttribute("pagination", pagination);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "busin/list";
	}

	/** 详情 **/
	@RequestMapping("detail")
	public String detail(@RequestParam(required = true) String id,
			Czjcommodity czjcommodity, HttpServletRequest req,HttpSession httpSession,
			HttpServletResponse resp, ModelMap model) {
		setBusinessId(model);
		setTypeId(model);
		try {
			// TODO 商品ID
			//id = "ySn781TFucmBTBRLhko";
			BusinessAndPic entity = czjcommodityService.getCommodity(id);
			model.addAttribute("entity", entity);
			List<CommImg> pic1 = new ArrayList<CommImg>(); // 0商品图片
			List<CommImg> pic2 = new ArrayList<CommImg>(); // 1商品默认图片
			List<CommImg> pic3 = new ArrayList<CommImg>();// 3商品文字介绍
			if (null != czjcommodity
					&& null != entity.getCzjcommodityimages()
					&& entity.getCzjcommodityimages().size() > 0) {
				for (int i = 0; i < entity.getCzjcommodityimages().size(); i++) {
					CommImg commImg=new CommImg();
					if (entity.getCzjcommodityimages().get(i).getPicType() == 0) {
					
							commImg.setImgId(entity.getCzjcommodityimages().get(i)
								.getId());
							commImg.setImagePath(entity.getCzjcommodityimages().get(i)
									.getImagePath());
							
							if(null!=entity.getCzjcommodityimages().get(i).getSequ()){
								
								commImg.setSequ(Integer.valueOf(entity.getCzjcommodityimages().get(i)
										.getSequ()));
							}
							pic1.add(commImg);
							
					}
					if (entity.getCzjcommodityimages().get(i).getPicType() == 1) {
						commImg.setImgId(entity.getCzjcommodityimages().get(i)
								.getId());
							commImg.setImagePath(entity.getCzjcommodityimages().get(i)
									.getImagePath());
							if(null!=entity.getCzjcommodityimages().get(i).getSequ()){
								
								commImg.setSequ(Integer.valueOf(entity.getCzjcommodityimages().get(i)
										.getSequ()));
							}
							pic2.add(commImg);
					}
					if (entity.getCzjcommodityimages().get(i).getPicType() == 3) {
						commImg.setImgId(entity.getCzjcommodityimages().get(i)
								.getId());
							commImg.setImagePath(entity.getCzjcommodityimages().get(i)
									.getImagePath());
							if(null!=entity.getCzjcommodityimages().get(i).getSequ()){
								
								commImg.setSequ(Integer.valueOf(entity.getCzjcommodityimages().get(i)
										.getSequ()));
							}
							pic3.add(commImg);
					}
				}

			}

			//商品规格
			List<Czjaftersales> czjaftersales=czjaftersalesService.getAfterByCommid(id);
			model.addAttribute("czjaftersales", czjaftersales);
			//商品售后服务
			List<Czjspecification>czjspecification=czjspecificationService.getSpecByCommid(id);
			model.addAttribute("czjspecification", czjspecification);
			
			model.addAttribute("pic1", pic1);
			model.addAttribute("pic2", pic2);
			model.addAttribute("pic3", pic3);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "查询商品表出错!详情：" + e.getMessage());
		}
		return "busin/detail";
	}
	
	/*删除商品图片*/
	@RequestMapping("delteImg")
	public String delteImg(String imgId,String id,HttpServletResponse response){
	
		Czjcommodityimage  czjcommodityimage=new Czjcommodityimage();
		try {
			czjcommodityimage.setId(imgId);
			czjcommodityimageService.deleteById(imgId);
			jsonResult(1, "", "", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "147", "", "", response);
		}
		
		return "redirect:/busin/list?id="+id;
		
	} 

	/** 新增或修改页面 **/
	@RequestMapping("add")
	public String add(BusinessAndPic czjcommodity, HttpServletRequest req,HttpSession httpSession,
			HttpServletResponse resp, ModelMap model) {
		setBusinessId(model);
		setTypeId(model);
		//TODO 商家ID
		
		Xyuser user=(Xyuser) httpSession.getAttribute("user");
		if(null!=user){
			
			Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(user.getUserId());
			if(null!=czjbusiness){
				model.addAttribute("businessId",czjbusiness.getId() );
			}else{
				return  "nobusin/nobusin";
			}
			
			
		}else{
			
			model.addAttribute("error","用户为空");
			return "nobusin/no";
		}
		//model.addAttribute("businessId","05dBejzjwinRERFxGrP" );
		if (StringUtils.isNotBlank(czjcommodity.getId())) {
			//TODO 商品ID
			czjcommodity = czjcommodityService.getCommodity(czjcommodity.getId());
			model.addAttribute("entity", czjcommodity);

		} else {
			model.addAttribute("entity", new BusinessAndPic());
		}
		List<CommImg> pic1 = new ArrayList<CommImg>(); // 商品图片
		List<CommImg> pic2 = new ArrayList<CommImg>(); // 1商品默认图片
		List<CommImg> pic3 = new ArrayList<CommImg>();// 3商品文字介绍
		if (null != czjcommodity
				&& null != czjcommodity.getCzjcommodityimages()
				&& czjcommodity.getCzjcommodityimages().size() > 0) {
			for (int i = 0; i < czjcommodity.getCzjcommodityimages().size(); i++) {
				CommImg commImg=new CommImg();
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 0) {
				
						commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						pic1.add(commImg);
				}
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 1) {
					commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						pic2.add(commImg);
				}
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 3) {
					commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						pic3.add(commImg);
				}
			}

		}
		model.addAttribute("pic1", pic1);
		model.addAttribute("pic2", pic2);
		model.addAttribute("pic3", pic3);
		return "busin/add";
	}
	
	/** 新增或修改第二个页面(商品 图片) **/
	@RequestMapping("add1")
	public String add1(BusinessAndPic czjcommodity, HttpServletRequest req,HttpSession httpSession,
			HttpServletResponse resp, ModelMap model) {
		setBusinessId(model);
		setTypeId(model);
		//TODO 商家ID
		
		Xyuser user=(Xyuser) httpSession.getAttribute("user");
		if(null!=user){
			
			Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(user.getUserId());
			if(null!=czjbusiness){
				model.addAttribute("businessId",czjbusiness.getId() );
			}else{
				return  "nobusin/nobusin";
			}
			
			
		}else{
			
			model.addAttribute("error","用户为空");
			return "nobusin/no";
		}
		//model.addAttribute("businessId","05dBejzjwinRERFxGrP" );
		if (StringUtils.isNotBlank(czjcommodity.getId())) {
			//TODO 商品ID
			czjcommodity = czjcommodityService.getCommodity(czjcommodity.getId());
			model.addAttribute("entity", czjcommodity);

		} else {
			model.addAttribute("entity", new BusinessAndPic());
		}
		List<CommImg> pic1 = new ArrayList<CommImg>(); // 商品图片
		List<CommImg> pic2 = new ArrayList<CommImg>(); // 1商品默认图片
		List<CommImg> pic3 = new ArrayList<CommImg>();// 3商品文字介绍
		if (null != czjcommodity
				&& null != czjcommodity.getCzjcommodityimages()
				&& czjcommodity.getCzjcommodityimages().size() > 0) {
			for (int i = 0; i < czjcommodity.getCzjcommodityimages().size(); i++) {
				CommImg commImg=new CommImg();
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 0) {
				
						commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						
						if(null!=czjcommodity.getCzjcommodityimages().get(i).getSequ()){
							
							commImg.setSequ(Integer.valueOf(czjcommodity.getCzjcommodityimages().get(i)
									.getSequ()));
						}
					
						pic1.add(commImg);
				}
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 1) {
					commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						if(null!=czjcommodity.getCzjcommodityimages().get(i).getSequ()){
							
							commImg.setSequ(Integer.valueOf(czjcommodity.getCzjcommodityimages().get(i)
									.getSequ()));
						}
						
						pic2.add(commImg);
				}
				if (czjcommodity.getCzjcommodityimages().get(i).getPicType() == 3) {
					commImg.setImgId(czjcommodity.getCzjcommodityimages().get(i)
							.getId());
						commImg.setImagePath(czjcommodity.getCzjcommodityimages().get(i)
								.getImagePath());
						if(null!=czjcommodity.getCzjcommodityimages().get(i).getSequ()){
							
							commImg.setSequ(Integer.valueOf(czjcommodity.getCzjcommodityimages().get(i)
									.getSequ()));
						}
						pic3.add(commImg);
				}
			}

		}
		model.addAttribute("pic1", pic1);
		model.addAttribute("pic2", pic2);
		model.addAttribute("pic3", pic3);
		return "busin/add_1";
	}

	/** 保存 **/
	@RequestMapping("save")
	public String save(
			Czjcommodity czjcommodity,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {
			if(czjcommodity.getInventory()==null){
				czjcommodity.setInventory(0);
			}
			if (StringUtils.isNotBlank(czjcommodity.getId())) { // 修改
				czjcommodityService.update(czjcommodity);
				return "redirect:/busin/add1?id="+czjcommodity.getId();

			} else {// 新增
				czjcommodity.setId(UUIDUtils.getUUID());
				// TODO 商家ID
				Xyuser user= (Xyuser) httpSession.getAttribute("user");
				if(null!=user){
					
					Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(user.getUserId());
					if(null!=czjbusiness){
						czjcommodity.setBusinessId(czjbusiness.getId());
					}else{
						return  "nobusin/nobusin";
					}
				}else{
					
					model.addAttribute("error","用户为空");
					return "nobusin/no";
				}
				String id= OrderType.COMMODITY.getIndex()+UUIDUtils.getUUID().substring(1);
				czjcommodity.setId(id);
				if(null==czjcommodity.getSoldOut()){
					czjcommodity.setSoldOut(1);//默认下架
				}
				czjcommodityService.insert(czjcommodity);
				return "redirect:/busin/add1?id="+id;//到商品图片页面 
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return null;
	}
	
	/** 商品图片详情上一步 （到商品基本信息页面）**/
	@RequestMapping("czjcommodityStep")
	public String czjcommodityStep(
			@RequestParam(required=true) String id,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {
			

			return "redirect:/busin/add?id="+id;
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return null;
	}
	
	/** 商品参数规格页面 **/
	@RequestMapping("czjspecificationAdd")
	public String czjspecificationAdd(
			Czjspecification czjspecification,String commodityId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			//新增 图片顺序
			String [] imgId=req.getParameterValues("imgId");
			String [] sequ=req.getParameterValues("sequ");
			
			String [] imgId1=req.getParameterValues("imgId1");
			String [] sequ1=req.getParameterValues("sequ1");
			
			Czjcommodityimage czjcommodityimage=null;
			if(null!=imgId){
			for(int i=0;i<imgId.length;i++){
				czjcommodityimage=new Czjcommodityimage();
				czjcommodityimage.setId(imgId[i]);
				
				String reg = "^\\d+$";
				if(Pattern.compile(reg).matcher(sequ[i]).find()){
					czjcommodityimage.setSequ(Integer.valueOf(sequ[i]));
				}else{
					czjcommodityimage.setSequ(100);
				}
				
				czjcommodityimageService.update(czjcommodityimage);
			}
			}
			
			if(null!=imgId1){
				
		
			for(int i=0;i<imgId1.length;i++){
				czjcommodityimage=new Czjcommodityimage();
				czjcommodityimage.setId(imgId1[i]);
				
				String reg = "^\\d+$";
				if(Pattern.compile(reg).matcher(sequ1[i]).find()){
					czjcommodityimage.setSequ(Integer.valueOf(sequ1[i]));
				}else{
					czjcommodityimage.setSequ(100);
				}
				
				czjcommodityimageService.update(czjcommodityimage);
			}
			
			}
			// 新增参评规格页面
			model.addAttribute("commodityId", commodityId);
			List<Czjspecification> czjspecifications=czjspecificationService.getSpecByCommid(commodityId);
		    model.addAttribute("list", czjspecifications);
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return "busin/Sales";
	}
	
	/** 商品参数规格页面 **/
	@RequestMapping("czjspecificationAdd_")
	public String czjspecificationAdd_(
			Czjspecification czjspecification,String commodityId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			model.addAttribute("commodityId", commodityId);
			  if(StringUtils.isNotBlank(czjspecification.getSpecificationId())){
				  Czjspecification c= czjspecificationService.queryById(czjspecification.getSpecificationId());
		            model.addAttribute("entity", c);
		        }else{
			            model.addAttribute("entity", new Czjspecification());
		        }
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return "busin/czjspecificationAdd";
	}
	/** 商品参数规格列表 **/
	@RequestMapping("czjspecificationSave")
	public void czjspecificationSave(
			Czjspecification czjspecification,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			 if(StringUtils.isNotBlank(czjspecification.getSpecificationId())){
				 	czjspecification.setUpdatetime(new Date());
	                czjspecificationService.update(czjspecification);
	                

	            }else{
	                czjspecification.setSpecificationId(UUIDUtils.getUUID());
	                czjspecification.setCreatetime(new Date());
	                czjspecificationService.insert(czjspecification);
	            }
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "", "", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		//return "ccommodityId="+czjspecification.getCommodityId();//跳转至售后服务
	}
	/** 商品参数规格新增活修改页面 **/
	@RequestMapping("czjspecificationSave_")
	public String czjspecificationSave_(
			Czjspecification czjspecification,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			model.addAttribute("commodityId", czjspecification.getCommodityId());
			  if(StringUtils.isNotBlank(czjspecification.getSpecificationId())){
		            czjspecification = czjspecificationService.queryById(czjspecification.getSpecificationId());
		            model.addAttribute("entity", czjspecification);
		        }else{
		        	 czjspecification = czjspecificationService.queryById(czjspecification.getSpecificationId());
			            model.addAttribute("entity", new Czjspecification());
		        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "busin/czjaftersalesAdd";//跳转至售后服务
	}
	/** 商品参数规格上一步 **/
	@RequestMapping("czjspecificationStep")
	public String czjspecificationStep(
			String id,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

				return "redirect:/busin/add1?id"+id;
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return null;
	}
	
	 /** 产品规格删除 **/
    @RequestMapping("/deletespec")
    public String delete(@RequestParam(required = true)String specificationId,String commodityId, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            czjspecificationService.deleteById(specificationId);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:/busin/czjspecificationAdd?commodityId="+commodityId;
    }
    
    /** 商品售后服务页面列表 **/
	@RequestMapping("czjaftersalesList")
	public String czjaftersalesList(
			Czjaftersales czjaftersales,String commodityId,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			model.addAttribute("commodityId", commodityId);
			List<Czjaftersales> c=czjaftersalesService.getAfterByCommid(commodityId);
		    model.addAttribute("list", c);

			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		
		return "busin/czjaftersalesList";
	}
	
	/** 商品售后服务页面 **/
	@RequestMapping("czjaftersalesAdd")
	public String czjaftersalesAdd(
			Czjaftersales czjaftersales,String commodityId,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			model.addAttribute("commodityId", commodityId);
			 if(StringUtils.isNotBlank(czjaftersales.getAftersalesId())){
		            czjaftersales = czjaftersalesService.queryById(czjaftersales.getAftersalesId());
		            model.addAttribute("entity", czjaftersales);
		        }else{
		        	model.addAttribute("entity", new Czjaftersales());
		        }
		        return "busin/czjaftersalesAdd";

			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return null;
	}
	
	/** 商品售后服务修改或新增 **/
	@RequestMapping("czjaftersalesSave")
	public void czjaftersalesSave(
			Czjaftersales czjaftersales,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			  if(StringUtils.isNotBlank(czjaftersales.getAftersalesId())){
	                czjaftersales.setUpdatetime(new Date());
	                czjaftersalesService.update(czjaftersales);


	            }else{
	                czjaftersales.setAftersalesId(UUIDUtils.getUUID());
	                czjaftersales.setCreatetime(new Date());
	                czjaftersalesService.insert(czjaftersales);
	            }
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
			jsonResult(0, "", "", "", resp);
		}
		jsonResult(1, "", "", "", resp);
	}
	/** 商品售后服务上一步 **/
	@RequestMapping("czjaftersalesStep")
	public String czjaftersalesStep(
			String commodityId,
			String imgId,HttpSession httpSession,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		try {

			return "redirect:/busin/czjaftersalesAdd?commodityId"+commodityId;
			
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", "保存商品表失败!详情：" + e.getMessage());
		}
		return null;
	}

	 /** 产品规格删除 **/
    @RequestMapping("/deleteafter")
    public String deleteafter(@RequestParam(required = true)String aftersalesId,String commodityId, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            czjaftersalesService.deleteById(aftersalesId);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:/busin/czjaftersalesList?commodityId="+commodityId;
    }
	@RequestMapping("uploadImg")  
	public void uploadImg(String imgid,String id,Integer picType,
			@RequestParam(value = "file", required = false) MultipartFile multipartFiles,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) {
		
		
		
		try {
		String pathRoot = req.getSession().getServletContext().getRealPath("");
			String filePath = "/upload/" + UUIDUtils.getUUID() ;
			File fileDir = new File(pathRoot + "/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			
			 
			multipartFiles.transferTo(new File(pathRoot + filePath+".jpg"));
		/*	 Thumbnails.of(new FileInputStream(new File(pathRoot + filePath+"."+imageName))).scale(1f).outputFormat("jpg").
				outputQuality(0.25f).toFile(new File(pathRoot + filePath+"czj"));*/
			
			/*ImageUtils.fromFile(new File(pathRoot + filePath+".jpg"))
			.quality(0.6f)
			.fixedGivenSize(true)
			.keepRatio(true)
			.bgcolor(Color.WHITE)	//白色背景
			.toFile(new File(pathRoot + filePath+"czj.jpg"));*/
			 
			if (multipartFiles != null && multipartFiles.getSize() > 0) {
				if(null!=imgid){
				
					Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
					czjcommodityimage.setId(imgid);
					czjcommodityimage.setImagePath(filePath+".jpg");
					//czjcommodityimage.setPicType(picType);
					czjcommodityimageService.update(czjcommodityimage);
					

				}else{ //新增
					
					if(picType==1){
						Map<String,Object> map=new HashMap<String, Object>();
							map.put("id",id );
							map.put("picType", picType);
						czjcommodityimageService.deleteByIdAndType(map); //默认 图片只有一张， 先将所有的图片删除
						//再做新增
						Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
						czjcommodityimage.setId(UUIDUtils.getUUID());
						czjcommodityimage.setCommodityId(id);
						czjcommodityimage.setPicType(picType);
						czjcommodityimage.setImagePath(filePath+".jpg");
						czjcommodityimageService.insert(czjcommodityimage);
						
					}else{
					Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
					czjcommodityimage.setId(UUIDUtils.getUUID());
					czjcommodityimage.setCommodityId(id);
					czjcommodityimage.setPicType(picType);
					czjcommodityimage.setImagePath(filePath+".jpg");
					czjcommodityimageService.insert(czjcommodityimage);
					
					}

				}
				
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
			jsonResult(0, "", "", "", resp);
		} catch (IOException e) {
			e.printStackTrace();
			jsonResult(0, "", "", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		
		/*try {
			String pathRoot = req.getSession().getServletContext().getRealPath("");
			String contentType = multipartFiles.getContentType();
			String voideType = contentType.substring(contentType.indexOf("/") + 1);
			String filePath = "/upload/" + UUIDUtils.getUUID() + "." + voideType;
			File fileDir = new File(pathRoot + "/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			multipartFiles.transferTo(new File(pathRoot + filePath));
			if (multipartFiles != null && multipartFiles.getSize() > 0) {
				if(null!=imgid){
				
						
					Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
					czjcommodityimage.setId(imgid);
					czjcommodityimage.setImagePath(filePath);
					//czjcommodityimage.setPicType(picType);
					czjcommodityimageService.update(czjcommodityimage);
					

				}else{ //新增
					
					if(picType==1){
						Map<String,Object> map=new HashMap<String, Object>();
							map.put("id",id );
							map.put("picType", picType);
						czjcommodityimageService.deleteByIdAndType(map); //默认 图片只有一张， 先将所有的图片删除
						//再做新增
						Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
						czjcommodityimage.setId(UUIDUtils.getUUID());
						czjcommodityimage.setCommodityId(id);
						czjcommodityimage.setPicType(picType);
						czjcommodityimage.setImagePath(filePath);
						czjcommodityimageService.insert(czjcommodityimage);
						
					}else{
					Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
					czjcommodityimage.setId(UUIDUtils.getUUID());
					czjcommodityimage.setCommodityId(id);
					czjcommodityimage.setPicType(picType);
					czjcommodityimage.setImagePath(filePath);
					czjcommodityimageService.insert(czjcommodityimage);
					
					}

				}
				
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		jsonResult(1, "", "", "", resp);*/
	}
	
	
	/** 删除 **/
	@RequestMapping("deleteImg")
	public String deleteImg(@RequestParam(required = true) String id, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		try {
			Czjcommodityimage czjcommodityimage = new Czjcommodityimage();
			czjcommodityimage.setId(id);
			czjcommodityimage.setDelFlag(1);
			czjcommodityimageService.update(czjcommodityimage);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", e.getMessage());
		}
		return "redirect:list.do";
	}

	/** 删除商品 **/
	@RequestMapping("delete.do")
	public String delete(@RequestParam(required = true) String id,
			Czjcommodity czjcommodity, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		try {
			Czjcommodity czjcommodity2 = new Czjcommodity();
			czjcommodity2.setId(id);
			czjcommodity2.setDelFlag(1);
			czjcommodityService.update(czjcommodity2);
			
			czjcommodity3Service.deleteByCommId(id);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", e.getMessage());
		}
		return "redirect:list.do";
	}
	
	@RequestMapping("/getAwardstockByBusin")
    public String getAwardstoc(@RequestParam(required = true) String commodityId,
                           HttpServletRequest req, HttpServletResponse resp,HttpSession httpSession,
                          ModelMap model) throws Exception {
    
			Map<String,Object> map=new HashMap<String, Object>();
		try {
			Xyuser user= (Xyuser) httpSession.getAttribute("user");
			if(null!=user){
				Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(user.getUserId());
				if(null!=czjbusiness){
				 map.put("businessId", czjbusiness.getId());
				 map.put("commodityId", commodityId);
					List<Map<String, Object>> czjawardstocks=czjawardstockService.getAwardstockByBusin(map);
					
				     for (int i = 0; i < czjawardstocks.size(); i++) {
				            if(czjawardstocks.get(i).get("id")!=null){
				            	czjawardstocks.get(i).put("ispermission",true);
				            }else{
				            	czjawardstocks.get(i).put("ispermission",false);
				            }
				        }
					model.addAttribute("czjawardstocks", czjawardstocks);
					model.addAttribute("commodityId", commodityId);
				}else{
					return  "nobusin/nobusin";
				}
			}else{
				
				model.addAttribute("error","用户为空");
				return "nobusin/no";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

   

        return "busin/czjawardstock";
    }

	
	 @RequestMapping("/saveCzjawardstock")
	    public void saveuser(@RequestParam(required = true) String commodityId,
	                         HttpServletRequest req, HttpServletResponse resp,
	                          ModelMap model) throws Exception {
	          
		 		Map<String, Object> map=new HashMap<String, Object>();
		 			map.put("commodityId",commodityId);
		 		 List<Czjcarela> list = czjcarelaService.getCzjcarelaList(map);//获取该商品所有关联优惠券
		       
		     	String[] awardstockIds = req.getParameterValues("awardstockIds[]");//前端选择的优惠券ID
		         List<String> userlist = new ArrayList<String>();
		         if(awardstockIds!=null&&awardstockIds.length!=0){
		             userlist = Arrays.asList(awardstockIds);
		         }


		         List<Czjcarela> savelist = new ArrayList<Czjcarela>();
		         for (String id : userlist) {
		        	 	Czjcarela czjcarela = new Czjcarela();
		             	czjcarela.setAwardstockId(id);
		             	czjcarela.setCommodityId(commodityId);
		             	czjcarela.setCarela(UUIDUtils.getUUID());
		             savelist.add(czjcarela);
		         }
		         if(list.size()!=0){
		        	 czjcarelaService.deleteByList(list);
		         }
		         if(savelist.size()!=0){
		        	 czjcarelaService.saveCareList(savelist);
		         }
	        

	    }
	 
	 /**
	  * 
	  * 方法名：shelves 上下架
	  * 创建人：RUI
	  * 时间：2017年7月18日-下午11:24:12 
	  * @param commodityId
	  * @param pageNo
	  * @param pageSize
	  * @param soldOut
	  * @param req
	  * @param resp
	  * @param model
	  * @return
	  * @throws Exception String
	  * @exception 
	  * @since  1.0.0
	  */
	 @RequestMapping("shelves")
	    public String shelves(@RequestParam(required = true) String commodityId,
	    		@RequestParam(required = true) String pageNo,
	    		@RequestParam(required = true) String pageSize,
	    		@RequestParam(required = true) Integer soldOut,
	                         HttpServletRequest req, HttpServletResponse resp,
	                          ModelMap model) throws Exception {
	          
		 Czjcommodity t=new Czjcommodity();
		 	t.setId(commodityId);
		 	t.setSoldOut(soldOut);
		 t.setUpdateTime(new Date());
		 czjcommodityService.update(t);
		 
		 if(soldOut==1){
			 czjcommodity3Service.deleteByCommId(commodityId);
		 }
		 		
		 return "redirect:/busin/list?pageNo="+pageNo;

	    }
	
	private void setBusinessId(ModelMap model) {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Map<String, Object>> listBusinessId = czjcommodityService
				.getListBusinessId(param);
		// map.put("name","");
		// map.put("value","");
		model.addAttribute("listBusinessId", listBusinessId);
	}

	private void setTypeId(ModelMap model) {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Map<String, Object>> listTypeId = czjcommodityService
				.getListTypeId(param);
		// map.put("name","");
		// map.put("value","");
		model.addAttribute("listTypeId", listTypeId);
	}

	private void setMsg(Czjcommodityimage czjcommodityimage,
			HttpServletRequest req, ModelMap model) {
		model.addAttribute("failed", req.getParameter("failed"));
		model.addAttribute("success", req.getParameter("success"));
		model.addAttribute("entity", czjcommodityimage);
	}

	private void setCommodityId(ModelMap model) {
		Map<String, Object> param = new HashMap<String, Object>();
		List<Map<String, Object>> listCommodityId = czjcommodityimageService
				.getListCommodityId(param);
		model.addAttribute("listCommodityId", listCommodityId);
	}



}
